//
//  LSZVideoPlaybackViewController.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/7/18.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZVideoPlaybackViewController.h"
#import "JDVideoModel.h"
#import "JDPlayerView.h"
#import "LSZVideoPlaybackViewController+LCBaiduMobAdPrerollNative.h"

@interface LSZVideoPlaybackViewController ()<JDPlayerDelegate,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>
@property(nonatomic,assign) BOOL applicationIdleTimerDisabled;
@property(nonatomic,assign) BOOL shouldRotate;

@property(nonatomic,strong) AVPlayer* avPlayer;

//请求得到的相关的数据
@property(nonatomic,strong)LSZRelatedVideoManager * relatedVideoManager;
@property(nonatomic,assign) BOOL isOrClickZan;//是否点赞
@property(nonatomic,strong) LSZThumbUpOrBlessingListForResourcesManager* ThumbUpOrBlessingListForResourcesMg;//获取点赞的数据
//离线
@property(nonatomic,strong) NSMutableArray * arrayGetOfflineData;
@property(nonatomic,strong) LSZOfflineVideoManager * VideoOfflineManager;

@end

@implementation LSZVideoPlaybackViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.applicationIdleTimerDisabled = [UIApplication sharedApplication].isIdleTimerDisabled;
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [LCFloatingWindow sharedInstance].hidden = YES;
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.player pauseContent];
    [self didPlayAdClose];
    [self baiduAdDealloc];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [UIApplication sharedApplication].idleTimerDisabled = self.applicationIdleTimerDisabled;
    [super viewWillDisappear:animated];
    [LCFloatingWindow sharedInstance].hidden = NO;
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate = self;
    self.shouldRotate = YES;
    self.recommendedClick = -1;
    [self addObserver];
    self.arrayGetOfflineData = [[NSMutableArray alloc]init];
    [self getTheRecommendedVideoFirst];//先获取推荐的视频

    [self.tableViewList registerClass:[LSZBDetailsPlayTableViewCell class] forCellReuseIdentifier:@"LSZBDetailsPlayTableViewCell"];
    [self.tableViewList registerClass:[LSZBInformationTableViewCell class] forCellReuseIdentifier:@"LSZBInformationTableViewCell"];
    [self.tableViewList registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
     ///请求广告
    [self pressToLoadAd];
    [self loadPrerollNative];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.videoFailed == YES) {
            self.videoFailed = NO;
        }else{
            [self playVideo];
        }
        [self.baiduMobAdPrerollNative.nativeAdView removeFromSuperview];
        [self didPlayAdClose];
    });
    [self addNotificationCenter];
    if (self.isOffline == NO) {
        [self initClickZanAll];
    }
}
-(void)addNotificationCenter
{
    //返回键
    __weak typeof(self) weakSelf = self;
    self.player.jdView.doneButtonBlock = ^{
        [weakSelf.player pauseContent];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    self.player.parseFailureBlock = ^{
        [weakSelf setStringWarning:@"解析失败!"];
        [weakSelf.player pauseContent];
    };
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InfoNotificationSwitchScreen:) name:@"switchScreen" object:nil];//切换屏幕
}
#pragma mark - 首次播放的url
- (void)playVideo
{
    JDVideoModel* videoModel = [[JDVideoModel alloc]init];
    if(self.isOffline == YES){
        videoModel.streamURL = [NSURL fileURLWithPath:self.playUrl];
    }else{
        self.playUrl = [NSString stringWithFormat:@"%@?%@",self.playUrl,[self usingRandomNumbers]];//使用随机数是可以
        videoModel.streamURL = [NSURL URLWithString:
                                [NSString stringWithFormat:@"?src=%@",[NSDate.new timeStampStr]]
                                      relativeToURL:[NSURL URLWithString:[self.playUrl codeString]]];
    }
    [self.player loadVideoModel:videoModel];
}
-(NSString *)stringUrl :(NSString *)string
{
//    NSString * playUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)string,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
//    NSString * playUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)string,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
//    return playUrl;
//    NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
//    NSString *encodeUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet];

    NSString*playUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return playUrl;
}
#pragma mark - App States
- (void)applicationWillResignActive
{
    self.player.jdView.countdownToHide = -1;
    if (self.player.state == JDPlayerStatePlaying){
        [self.player pauseContent:NO recordCurrentTime:YES completionHandler:nil];
    }
}
- (void)applicationDidBecomeActive
{
    self.player.jdView.countdownToHide = -1;
}
#pragma mark - 所有的播放完毕 也会走这个方法
- (void)videoPlayer:(JDPlayer*)videoPlayer didPlayToEnd:(JDVideoModel *)videoModel
{
    NSInteger beForeRow = self.recommendedClick;
    if(self.isOffline == YES){
        if (beForeRow == self.VideoOfflineManager.arrayData.count-1) {
            NSLog(@"最后一个最后一个");
            return;
        }
    }else{
        if (beForeRow == self.relatedVideoManager.arrayData.count-1) {
            NSLog(@"最后一个最后一个");
            return;
        }
    }
    self.recommendedClick = beForeRow+1;
    [self.player pauseContent];
    [self.baiduMobAdPrerollNative.nativeAdView removeFromSuperview];
    [self didPlayAdClose];
    [self loadPrerollNative];
    
    [self butInVideo];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格  和结束刷新
        if(self.videoFailed == YES){
            self.videoFailed = NO;
        }else{
            [self loadTheVideo];//再更新URL
        }
    });
    NSLog(@"走这个了走这个了走这个了走这个了走这个了走这个了走这个了走这个了");
}
- (void)videoPlayer:(JDPlayer *)videoPlayer didNextVideoButtonPressed:(JDVideoModel *)videoModel
{
//    [self videoPlayer:videoPlayer didPlayToEnd:videoModel];

    NSLog(@"截屏");
    float currentTime = CMTimeGetSeconds([_player.avPlayer currentCMTime]) - 0.5f;
    NSLog(@"[_player.avPlayer currentCMTime] = %f", currentTime);
    
    NSURL *url = [NSURL URLWithString:
                  [NSString stringWithFormat:@"?src=%@",[NSDate.new timeStampStr]]
                        relativeToURL:[NSURL URLWithString:[self.playUrl codeString]]];
    AVAsset *asset = [AVAsset assetWithURL:url];
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    // 在苹果API中看到 Asynchronously 词汇需要注意回调函数的多线程
    @weakify(self)
    [SVProgressHUD showSuccessWithStatus:@"截屏成功!"];

    [generator generateCGImagesAsynchronouslyForTimes:@[@(currentTime)] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            @strongify(self)
            UIImage *img = [UIImage imageWithCGImage:image];
            JKAlertView *alertView = [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)];
            [alertView addAction:[JKAlertAction actionWithTitle:@"微信分享" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                [self shareNoUIWithImageArray:@[img] url:nil title:@"九酷福音" contentMessage:@"九酷福音" type:(SSDKContentTypeImage) platformType:(SSDKPlatformSubTypeWechatSession)];
            }]];
            [alertView addAction:[JKAlertAction actionWithTitle:@"朋友圈分享" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                [self shareNoUIWithImageArray:@[img] url:nil title:@"九酷福音" contentMessage:@"九酷福音" type:(SSDKContentTypeImage) platformType:(SSDKPlatformSubTypeWechatTimeline)];
            }]];
            alertView.enableDeallocLog(YES).show().setDismissComplete(^{
                [SVProgressHUD dismiss];
            });
        });
    }];

}

- (void)handleErrorCode:(JDPlayerErrorCode)errorCode track:(JDVideoModel *)track customMessage:(NSString*)customMessage
{
    NSLog(@"errorCode : %ld,message : %@ , url : %@",(long)errorCode,customMessage,track.streamURL);
}
#pragma mark - Orientation
- (BOOL)shouldAutorotate
{
    return self.shouldRotate;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return self.shouldRotate;
}
- (JDPlayer *)player
{
    if(!_player){
        _player = [[JDPlayer alloc] init];
        _player.delegate = self;
        [self.view addSubview:_player.jdView];
        if (iPhoneX ) {
            _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16+24);//进度条
        }else{
            _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16);//进度条
        }
//        _player.jdView.frame = CGRectMake(0, 0, self.view.frame.size.width,ScreenWidth*9/16);//进度条
    }
    return _player;
}
- (BOOL)prefersStatusBarHidden
{
    return YES;
}
-(void)InfoNotificationSwitchScreen:(NSNotification *)notification
{
    NSDictionary * dic = notification.userInfo;
    NSString * screen = dic[@"screen"];
    if ([screen isEqualToString:@"1"]) {
        self.tableViewList.hidden = YES;
    }else{
        self.tableViewList.hidden = NO;
    }
}
- (void)addObserver
{
    NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}
#pragma mark - 先获取推荐的视频
-(void)getTheRecommendedVideoFirst
{
    if(self.isOffline == YES){
        NSArray * arrayGetData = [[NSArray alloc]initWithContentsOfFile:[LSZSpecialPackaging saveTheNameOfVideo]];
        [self.arrayGetOfflineData addObjectsFromArray:arrayGetData];
        if (self.arrayGetOfflineData.count >0) {
            self.arrayGetOfflineData=(NSMutableArray *)[[self.arrayGetOfflineData reverseObjectEnumerator] allObjects];
            self.VideoOfflineManager = [[LSZOfflineVideoManager alloc]initWithOfflineVideo:self.arrayGetOfflineData];
            [self.tableViewList reloadData];
        }
    }else{
        [LSZRequestResolutionDic getTheRecommendedVideoFirstData:^(BOOL isOk, NSString * string, LSZRelatedVideoManager * manager) {
            if (isOk == YES) {
                self.relatedVideoManager = manager;
                if (self.isOffline == YES) {
                    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
                    [self.tableViewList reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                }else{
                    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:2];
                    [self.tableViewList reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                }
            }
        }];
    }
}
#pragma mark - 用户对资源点赞    type,资源类型     1,音频 2，视频 3，文章，6祷告，7见证
#pragma mark - 对原始资源点赞
-(void)clickZanButImageShou:(UIGestureRecognizer *)send
{
    [self clickZanBut];
}
-(void)clickZanBut
{
    if([[_UserM usercode] isEqualToString:@""]){
        [self setStringWarning:@"请先登录,然后再点赞呀!"];
        return;
    }else{
        if (self.isOrClickZan == YES) {
            [self setStringWarning:@"不能重复点赞!"];
            return;
        }
        [LSZRequestData videoIsThumbUp:self.id_id :@"0" :^(BOOL isOk, NSString * str, NSDictionary * dic) {
            LSZBInformationTableViewCell * cell = (LSZBInformationTableViewCell *)[self.tableViewList cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
            if (isOk == YES) {
                self.isOrClickZan = YES;
                [self setStringWarning:@"点赞成功!"];
                cell.imageViewShou.image = [UIImage imageNamed:@"红手"];
                cell.labelShou.text = [NSString stringWithFormat:@"已赞:%ld",(long)self.zan+1];
            }else{
                if([str isEqualToString:@"已点赞"]){
                    cell.imageViewShou.image = [UIImage imageNamed:@"红手"];
                    self.isOrClickZan = YES;
                }
                [self setStringWarning:str];
            }
        }];
    }
}
#pragma mark - 分享
-(void)clickShareButImageView
{
    NSLog(@"self.recommendedClick = %zd", self.recommendedClick);
    OSMessage *msg = [[OSMessage alloc] init];
    msg.title = self.titleString;
    msg.desc = self.author;
    
    msg.link = self.playUrl;
    msg.thumbnail = UIImageJPEGRepresentation([UIImage imageNamed:@"我的_设置_关于"],0.26);
    //video
    msg.multimediaType = OSMultimediaTypeVideo;
    if (self.recommendedClick > -1) {
        LSZRelatedVideoMg * mg = nil;
        mg = self.relatedVideoManager.arrayData[self.recommendedClick];
        msg.title = mg.name;
        msg.desc = mg.author;
        msg.link = mg.mp4_url;
        [self clickShareButWithMsg:msg pic:mg.pic];
        return;
    }
    [self clickShareButWithMsg:msg pic:self.pic];
}
- (void)clickShareButWithMsg:(OSMessage *)msg pic:(NSString *)pic
{
    NSLog(@"分享");
    JKAlertView *alertView = [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)];
    
    if ([OpenShare isWeixinInstalled]) {
        [alertView addAction:[JKAlertAction actionWithTitle:@"微信分享" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
            [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
            } Fail:^(OSMessage *message, NSError *error) {
            }];
        }]];
        [alertView addAction:[JKAlertAction actionWithTitle:@"朋友圈分享" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
            [OpenShare shareToWeixinTimeline:msg Success:^(OSMessage *message) {
            } Fail:^(OSMessage *message, NSError *error) {
            }];
        }]];
    }
    if (pic != nil) {
        //        msg.thumbnail = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.pic]];
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:pic] options:(0) progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            //处理下载进度
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image) {
                msg.thumbnail = UIImageJPEGRepresentation(image, 0.1);
            }
            alertView.enableDeallocLog(YES).show().setDismissComplete(^{
            });
        }];
    }else{
        alertView.enableDeallocLog(YES).show().setDismissComplete(^{
        });
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]){
        return NO;
    }
    return  YES;
}
#pragma mark - 获取点赞的数据
-(void)initClickZanAll
{
    [LSZRequestData videoIsThumbUp:self.id_id :@"1" :^(BOOL isOk, NSString * str, NSDictionary * dic) {
        LSZBInformationTableViewCell * cell = (LSZBInformationTableViewCell *)[self.tableViewList cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
        if (isOk == YES) {
            cell.imageViewShou.image = [UIImage imageNamed:@"红手"];
            cell.labelShou.text = [NSString stringWithFormat:@"已赞:%ld",(long)self.zan];
            self.isOrClickZan = YES;
        }else{
            cell.imageViewShou.image = [UIImage imageNamed:@"视频_没点"];
            cell.labelShou.text = [NSString stringWithFormat:@"已赞:%ld",(long)self.zan];
            self.isOrClickZan = NO;
        }
    }];
}
#pragma mark ________________ 目录列表______________________
-(UITableView *)tableViewList
{
    if (_tableViewList == nil) {
        _tableViewList = [[UITableView alloc]initWithFrame:CGRectMake(0,ScreenWidth*9/16, ScreenWidth, ScreenHeight-ScreenWidth*9/16) style:UITableViewStyleGrouped];
        if (iPhoneX) {
            _tableViewList.frame = CGRectMake(0,ScreenWidth*9/16+24, ScreenWidth, ScreenHeight-ScreenWidth*9/16-24);
        }
        _tableViewList.dataSource =self;
        _tableViewList.delegate = self;
        _tableViewList.estimatedRowHeight=0;
        _tableViewList.estimatedSectionFooterHeight =0;
        _tableViewList.estimatedSectionHeaderHeight =0;
        [self.view addSubview:_tableViewList];
    }
    return _tableViewList;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.isOffline == YES){
        return 2;
    }else{
        return 3;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.isOffline == YES){
        if(section == 0){
            return 1;
        }else{
            return  self.VideoOfflineManager.arrayData.count;
        }
    }else{
        if(section == 0){
            return 1;
        }else if (section==1 ){
            return 1;

        }else{
            return self.relatedVideoManager.arrayData.count;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.isOffline == YES){
         if (indexPath.section == 0) {
            if (self.adViewArray.count > 0) {
                return LCPicsHeight-50;
            }else{
                return 0;
            }
        }else{
            if (ScreenWidth == 320) {
                //5
                return 50;
            }else if(ScreenWidth == 375){
                // 6 7
                return 55;
            }else {
                //plus
                return 60;
            }
         }
    }else{
        if (indexPath.section == 0) {
            return  140;
        }else if (indexPath.section == 1) {
            if (self.adViewArray.count > 0) {
                return LCPicsHeight-50;
            }else{
                return 0;
            }
        }else{
            if (ScreenWidth == 320) {
                //5
                return 50;
            }else if(ScreenWidth == 375){
                // 6 7
                return 55;
            }else {
                //plus
                return 60;
            }
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(self.isOffline == YES){
        if (section == 0) {
            return 0.0001;
        }
        return 10;
    }else{
        if (section == 1) {
            return 0.0001;
        }
        return 10;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0&&self.isOffline == NO) {
        LSZBInformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZBInformationTableViewCell" forIndexPath:indexPath];
        [self viewCellForRowSection:indexPath :cell];
        return cell;
    }else if ((indexPath.section == 1&&self.isOffline == NO)||(indexPath.section == 0&&self.isOffline == YES)) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellIdentifier"];
        }
        if (self.adViewArray.count > 0)
        {
            BaiduMobAdNativeAdView *view = [self.adViewArray objectAtIndex:indexPath.row];
            view.tag = 0;
            [[cell viewWithTag:0] removeFromSuperview];
            view.frame =
            CGRectMake(10, 15, [UIScreen mainScreen].bounds.size.width-10, LCPicsHeight);
            UIView *bgView = [[UIView alloc] init];
            bgView.frame =
            CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, LCPicsHeight-50);
            bgView.clipsToBounds = YES;
            [cell.contentView addSubview:bgView];
            [bgView addSubview:view];
            [self sendVisibleImpressionAtIndexPath:indexPath];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        if(self.isOffline == YES ){
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            }
            if (self.VideoOfflineManager.arrayData.count > indexPath.row) {
                LSZOfflineVideoMg * VideoMg= nil;
                VideoMg = self.VideoOfflineManager.arrayData[indexPath.row];
                cell.textLabel.text =  [NSString stringWithFormat:@" %ld  %@",(long)indexPath.row+1,VideoMg.title];
                [LSZSpecialPackaging setLabelAdaptiveSize:cell.textLabel font:14];
                if ([self.titleString isEqualToString:VideoMg.title]) {
                    cell.textLabel.textColor = redUIColor;
                }else{
                    cell.textLabel.textColor = titleColorLSZ;
                }
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            LSZBDetailsPlayTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZBDetailsPlayTableViewCell" forIndexPath:indexPath];
            [self contentWithCellForRow:indexPath :cell];
            return cell;
        }
    }
}
-(void)viewCellForRowSection :(NSIndexPath *)indexPath :(LSZBInformationTableViewCell*)cell
{
    NSString * strClick = [LSZSpecialPackaging theNumberViewsForTheAlbumAhanges:[NSString stringWithFormat:@"%ld",(long)self.zan]];
    if (self.isOrClickZan == YES) {
        cell.imageViewShou.image = [UIImage imageNamed:@"红手"];
        cell.labelShou.text = [NSString stringWithFormat:@"已赞:%@",strClick];
    }else{
        cell.imageViewShou.image = [UIImage imageNamed:@"视频_没点"];
        cell.labelShou.text = [NSString stringWithFormat:@"赞:%@",strClick];
    }
    cell.labelTitle.text = [NSString stringWithFormat:@"主题:%@",self.titleString];
    cell.labelAuthor.text = [NSString stringWithFormat:@"作者:%@",self.author];
    cell.labelClick.text = [NSString stringWithFormat:@"浏览:%@次",self.click];

    @weakify(self)
    [cell.imageViewShou tapGesture:^(UIGestureRecognizer *ges) {
        @strongify(self)
        [self clickZanButImageShou:ges];
    }];
    [cell.butZan tapGesture:^(UIGestureRecognizer *ges) {
        @strongify(self)
        [self clickZanButImageShou:ges];
    }];
    [cell.butShare tapGesture:^(UIGestureRecognizer *ges) {
        @strongify(self)
        [self clickShareButImageView];
    }];
    [cell.imageViewShare tapGesture:^(UIGestureRecognizer *ges) {
        @strongify(self)
        [self clickShareButImageView];
    }];
    [cell.labelShare tapGesture:^(UIGestureRecognizer *ges) {
        @strongify(self)
        [self clickShareButImageView];
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
-(void)contentWithCellForRow :(NSIndexPath *)indexPath :(LSZBDetailsPlayTableViewCell *)cell
{
    LSZRelatedVideoMg * mg = nil;
    mg = self.relatedVideoManager.arrayData[indexPath.row];
    cell.labelNumber.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    NSString * strTitle = [NSString stringWithFormat:@"%@",mg.name];
    cell.labelTitle.text = strTitle;
//    [LSZSpecialPackaging adaptiveWidth:cell.labelTitle str:cell.labelTitle.text sizeMaxWidth:ScreenWidth-60 sizeMaxHeight:cell.labelTitle.frame.size.height];
//    CGRect rect = cell.imageViewPlay.frame;
//    rect.origin.x = CGRectGetMaxX(cell.labelTitle.frame)+10;
//    cell.imageViewPlay.frame = rect;
    //次数
    cell.labelPlayNumber.text = [NSString stringWithFormat:@"%@",mg.click];
//    [LSZSpecialPackaging adaptiveWidth:cell.labelPlayNumber str:cell.labelPlayNumber.text sizeMaxWidth:ScreenWidth-50-CGRectGetMaxX(cell.imageViewPlay.frame) sizeMaxHeight:cell.labelPlayNumber.frame.size.height];
//    CGRect rectPlays = cell.labelPlayNumber.frame;
//    rectPlays.origin.x = CGRectGetMaxX(cell.imageViewPlay.frame)+2;
//    cell.labelPlayNumber.frame = rectPlays;
//    if (CGRectGetMaxX(cell.labelPlayNumber.frame) > ScreenWidth-60) {
//        cell.imageViewPlay.hidden = YES;
//        cell.labelPlayNumber.hidden = YES;
//    }else{
//        cell.imageViewPlay.hidden = NO;
//        cell.labelPlayNumber.hidden = NO;
//    }
    cell.imageDownload.tag= indexPath.row+1;
    cell.butDownload.tag  = indexPath.row+1;
    UITapGestureRecognizer*singleTap3=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toCityByClickedDownload:)];
    singleTap3.numberOfTouchesRequired = 1; //手指数
    singleTap3.numberOfTapsRequired = 1; //tap次数
    singleTap3.delegate= self;
    [cell.imageDownload addGestureRecognizer:singleTap3];
    if ([self.titleString isEqualToString:mg.name]) {
        cell.isOrPlayer = YES;
    }else{
        cell.isOrPlayer = NO;
    }
    [cell.butDownload addTarget:self action:@selector(clickDownload:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0&&self.isOffline == NO){
        return;
    }else if ((indexPath.section == 1&&self.isOffline == NO)||(indexPath.section == 0&&self.isOffline == YES)){
        NSLog(@"广告");
    }else{
        NSInteger beForeRow = self.recommendedClick;
        if(beForeRow == indexPath.row){
            return;
        }
        self.recommendedClick = indexPath.row;
//        self.VideoOfflineManager.arrayData[self.recommendedClick];
        if(self.VideoOfflineManager.arrayData.count > self.recommendedClick){
            return;
        }
        [self.player pauseContent];
        [self.baiduMobAdPrerollNative.nativeAdView removeFromSuperview];
        [self didPlayAdClose];
        [self loadPrerollNative];
        [self butInVideo];//先刷新界面
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格  和结束刷新
            if(self.videoFailed == YES){
                self.videoFailed = NO;
            }else{
                [self loadTheVideo];//再更新URL
            }
        });
    }
}
#pragma mark - 切换视频和音频 beforeRow之前点击的row  isVideoOrAudio视频1 音频2 离线没用最后一个字段
-(void)butInVideo
{
    if (self.isOffline == YES) {
        LSZOfflineVideoMg * manager= nil;
        manager = self.VideoOfflineManager.arrayData[self.recommendedClick];
        self.titleString = manager.title;
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
        [self.tableViewList reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        LSZRelatedVideoMg * mg = nil;
        mg = self.relatedVideoManager.arrayData[self.recommendedClick];
        [LSZRequestData UpdateVideoPlaybackTimes:mg.id_id :^(BOOL isOk, NSString * str, NSDictionary * dic) {
            if (isOk == YES) {
                mg.click = [NSString stringWithFormat:@"%ld",(long)[mg.click intValue] +1];
            }
            self.id_id = mg.album_id;
            self.titleString = mg.name;
            self.author = mg.author;
            self.click = mg.click;
            self.zan = [mg.zan integerValue];
            [self initClickZanAll];
            [self.tableViewList reloadData];
        }];
    }

}
-(void)loadTheVideo
{
    JDVideoModel* nextTrack = [[JDVideoModel alloc]init];
    if (self.isOffline == YES) {
        LSZOfflineVideoMg * manager= nil;
        manager = self.VideoOfflineManager.arrayData[self.recommendedClick];
        NSString * str1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
        self.playUrl = [str1 stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",manager.title]];
        nextTrack.streamURL = [NSURL  fileURLWithPath:self.playUrl];
        if(self.recommendedClick == self.VideoOfflineManager.arrayData.count - 1){
            nextTrack.hasNext = NO;//最后一个就设置no
        }else{
            nextTrack.hasNext = YES;
        }
        [self.player loadVideoModel:nextTrack];

    }else{
        LSZRelatedVideoMg * mg = nil;
        mg = self.relatedVideoManager.arrayData[self.recommendedClick];
//        self.playUrl = mg.mp4_url;
        self.playUrl = [NSString stringWithFormat:@"%@?%@",mg.mp4_url,[self usingRandomNumbers]];//使用随机数是可以
        nextTrack.streamURL = [NSURL URLWithString:[self stringUrl:self.playUrl]];
        if(self.recommendedClick == self.relatedVideoManager.arrayData.count - 1){
            nextTrack.hasNext = NO;//最后一个就设置no
        }else{
            nextTrack.hasNext = YES;
        }
        [self.player loadVideoModel:nextTrack];
    }
}
-(NSString *)usingRandomNumbers
{
   NSString * str = [NSString stringWithFormat:@"%ld",(long)arc4random() % 10000];
    return str;
}
#pragma mark - __________________下载______________________
#pragma mark - 下载
-(void)toCityByClickedDownload:(UIGestureRecognizer *)sender
{
    UITapGestureRecognizer *tap = (UITapGestureRecognizer*)sender;
    UIImageView * imageView = (UIImageView*) tap.view;
    NSInteger tagClicked = (NSInteger)imageView.tag;
    [self clickDownloadRow: tagClicked-1];
}
-(void)clickDownload:(UIButton *)send
{
    [self clickDownloadRow:send.tag-1];
}
-(void)clickDownloadRow:(NSInteger)row
{
    LSZRelatedVideoMg * mg = nil;
    mg = self.relatedVideoManager.arrayData[row];
    NSArray * arrayGetData = [[NSArray alloc]initWithContentsOfFile:[LSZSpecialPackaging saveTheNameOfVideo]];
    for (NSDictionary * dic in arrayGetData) {
        NSString * name = NSStr(dic[@"title"]);
        if ([name isEqualToString:mg.name]) {
            if([dic[@"style"] isEqualToString:@"1"]){
                [self initWithtring:@"该视频已缓存过!"];
                return;
            }
        }
    }
    [self initWithtring:@"缓存中....."];
    NSString * urlStr = [[NSString alloc]init];
    urlStr =[mg.mp4_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
#pragma mark -------------------- 断点下载------------------
    //构建URL
    //    NSURL *url = [NSURL URLWithString:urlStr];
    //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    //断点下载
    //    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    //    [connection start];
#pragma mark ------------------------多任务下载-----------------
    //这个是完整的下载
    NSURL *url=[NSURL URLWithString:urlStr];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    //2.创建请求
    //3.创建会话（这里使用了一个全局会话）并且启动任务
    NSURLSession *session=[NSURLSession sharedSession];
    NSString *savePath= [LSZSpecialPackaging DownloadTheVideo:[NSString stringWithFormat:@"%@.mp4",mg.name]];
    NSMutableArray * mutArrayAdd = [[NSMutableArray alloc]initWithArray:arrayGetData];
    //    NSString * style = [[NSString alloc]init];//视频yes  音频no
    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]init];
    //    style = @"1";
    mutDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:self.id_id,@"id_id",mg.name,@"title",mg.pic,@"imageViewUrl",mg.name,@"name",@"1",@"style",nil];
    [mutArrayAdd addObject:mutDic];
    [mutArrayAdd writeToFile:[LSZSpecialPackaging saveTheNameOfVideo] atomically:YES];
    NSURL *saveUrl=[NSURL fileURLWithPath:savePath];

    NSURLSessionDownloadTask *downloadTask=[session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error){
        if (!error) {
            //注意location是下载后的临时保存路径,需要将它移动到需要保存的位置
            NSError *saveError;
            [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError];
            if (!saveError) {
                //通知主线程刷新
                dispatch_async(dispatch_get_main_queue(), ^{
                    //回调或者说是通知主线程刷新，
                    [self initWithtring:@"缓存成功!"];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    //回调或者说是通知主线程刷新，
                    [self initWithtring:saveError.localizedDescription];
                });
            }
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [self initWithtring:error.localizedDescription];
                //删除缓存失败的文件目录
                NSArray * arrayGetDataMove = [[NSArray alloc]initWithContentsOfFile:[LSZSpecialPackaging saveTheNameOfVideo]];
                NSMutableArray * arrayMove = [[NSMutableArray alloc]initWithArray:arrayGetDataMove];
                for (int i = 0; i<arrayGetDataMove.count; i++) {
                    NSDictionary * dic = arrayGetDataMove[i];
                    NSString * title = NSStr(dic[@"title"]);
                    if ([title isEqualToString:mg.name]) {
                        [arrayMove removeObjectAtIndex:i];
                    }
                }
                [arrayMove writeToFile:[LSZSpecialPackaging saveTheNameOfVideo] atomically:YES];
                NSLog(@"删除已添加的文件名字");
            });
        }
    }];
    [downloadTask resume];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
     _native = nil;
    for (UIView *adview in _adViewArray) {
        [adview removeFromSuperview];
    }
    [_adViewArray removeAllObjects];
    _adViewArray = nil;
    _adsArray = nil;
    self.navigationController.delegate = nil;
    [self didPlayAdClose];
}
@end
